<?php
/*
 module:		发布管理
 create_time:	2022-03-09 16:30:59
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\model\ZhWechatMediaLog;
use app\api\service\ZhAuthenticationService;
use app\api\model\ZhAuthentication as ZhAuthenticationModel;
use app\backend\model\ZhTel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use wechat\MediaCheckAsync;
use wechat\MsgSecCheck;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\api\model\ZhCollection as ZhCollectionModel;
use app\api\model\ZhMatchmaker as ZhMatchmakerModel;

class ZhAuthentication extends Common
{
    /**
     * @api             {get} api/ZhAuthentication/index 01、首页数据列表
     * @apiGroup        ZhAuthentication
     * @apiVersion      1.0.0
     * @apiDescription  首页数据列表
     * @apiParam (输入参数：) {int}            [limit] 每页数据条数（默认20）
     * @apiParam (输入参数：) {int}            [page] 当前页码
     * @apiParam (输入参数：) {string}        [real_name] 真实姓名
     * @apiParam (输入参数：) {int}            [gender] 性别 男|1|success,女|0|warning
     * @apiParam (输入参数：) {string}        [date_birth] 出生日期
     * @apiParam (输入参数：) {string}        [city] 所在地城市
     * @apiParam (输入参数：) {int}            [marital_status] 婚姻状况 未婚|0|success,离婚|1|warning,离异|2|primary ,丧偶|4|info
     * @apiParam (输入参数：) {int}            [have_children] 有无子女 有|1|success,没有|0|warning
     * @apiParam (输入参数：) {string}        [nation] 民族
     * @apiParam (输入参数：) {string}        [occupation] 职业
     * @apiParam (输入参数：) {string}        [income] 月收入
     * @apiParam (输入参数：) {int}            [purchase_status] 购房情况 已购房|0|success,和家人同住|1|warning,租房|2|primary,婚后买房|3|info
     * @apiParam (输入参数：) {int}            [vehicle_status] 购车情况 已购车|1|success,未购车|0|warning
     * @apiParam (输入参数：) {int}            [is_smoking] 是否抽烟 是|1|success,否|0|warning
     * @apiParam (输入参数：) {int}            [is_drink] 是否喝酒 是|1|success,否|0|warning
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据
     * @apiParam (成功返回参数：) {string}        array.data.list 返回数据列表
     * @apiParam (成功返回参数：) {string}        array.data.count 返回数据总数
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"查询失败"}
     */
    function index()
    {
        $wxapp_id       = $this->request->get('wxapp_id');
        $gender         = $this->request->get('sex', '', 'serach_in'); // 性别 男 女
        $education      = $this->request->get('xueli', '', 'serach_in'); // 学历
        $maritalStatus  = $this->request->get('hunshi', '', 'serach_in');// 婚史 未婚 离异 丧偶
        $city           = $this->request->get('city', '', 'serach_in');// 城市
        $province=      $this->request->get('province', '', 'serach_in');
        $county         = $this->request->get('county', '', 'serach_in');//地区
        $giftNum        = $this->request->get('liwunum', '', 'serach_in');// 礼物量
        $giveNum        = $this->request->get('shoucangnum', '', 'serach_in');// 收藏量
        $income         = $this->request->get('income', '0', 'intval');// 年收入, 新的参数  传的是数值 不限：0 ，10万以下：1 ，10-15万：2 ，16-20万：3， 20-50万：4 ，50-100万：5 ，100万以上：6
        $age            = $this->request->get('age', '', 'serach_in');// 年龄
        $realName       = $this->request->get('real_name', '', 'serach_in');// 姓名
        $occupation     = $this->request->get('occupation', '', 'serach_in');// 职业
        $is_top= $this->request->get('is_top', '', 'serach_in');//

        $tags           = $this->request->get('tags', '', 'serach_in');// 小程序 热门专区的标签
        $recommend_tags = $this->request->get('recommend_tags', '', 'serach_in');// 推荐标签
        $matchmaker_id = $this->request->get('matchmaker_id', '', 'serach_in'); // 红娘id---红娘旗下
        $show_type = $this->request->get('show_type', '', 'serach_in');//查询类型 1公开 2红娘所属佳人

        $isVip     = $this->request->get('is_vip', '', 'serach_in');// 为真则是推广页面发起的请求
        $show_home = $this->request->get('show_home', 0, 'intval');
        $purchase_status= $this->request->get('purchase_status', 0, 'intval');//购房情况
        $vehicle_status= $this->request->get('vehicle_status', 0, 'intval');//购车情况

        $min_height         = $this->request->get('min_height', 0, 'serach_in');// 最小身高
        $max_height        = $this->request->get('max_height', 0, 'serach_in');// 最大身高
        $animal             = $this->request->get('animal', '', 'serach_in');// 属相
        $have_children        = $this->request->get('have_children', 0);// 有无子女  1是 2否
        $belief        = $this->request->get('belief', '');// 信仰
        //关键词搜索
        $keyword=$this->request->get('keyword', '');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        // 获取用户id 用以判断用户是否登录
        $token = $this->request->header('Authorization');
        $uid   = 0;
        if ($token) {
            $jwt = Jwt::getInstance();
            $jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))
                ->setSecrect(config('my.jwt_secrect'))
                ->setToken($token);
            $uid  = $jwt->decode()->getClaim('uid');
            $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
            if (!$user) {
                return $this->ajaxReturn($this->errorCode, '未知用户');
            }
        }
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');
        $where   = [];
        $where2="";
        //新加的参数
        if($purchase_status > 0){
            $where[] = ['a.purchase_status', '=', $purchase_status];
        }
        if($vehicle_status > 0){
            $where[] = ['a.vehicle_status', '=', $vehicle_status];
        }
        //lwx   所属红娘
        if($matchmaker_id>0){
            // $show_type 1公开佳人资料，要求已审核   2所属红娘资料，所有
            $where[] = ['a.matchmaker_id', '=', $matchmaker_id];
            if(intval($show_type)==1){
                $where[] = ['a.status', '=', 1];
            }
        }else{
            $where[] = ['a.is_show', '=', 1];
            $where[] = ['a.status', '=', 1];
            $where[] = ['a.is_frame', '=', 1];
            // 如果$isVip为真的话则说明是推广中心发起的请求, 查询字段 head_portrait real_name is_vip is_collection age height city
            if ($isVip == 1) {
                $uidList = MemberModel::where(['p_id' => $uid, 'wxapp_id' => $wxapp_id])
                    ->column('uid');
                if(!$uidList){
                    $uidList = [-1];
                }
                $where[] = ['a.u_id', 'in', $uidList];
            }
            //置顶
            if ($show_home == 1) {
                $uidList = MemberModel::where(['wxapp_id' => $wxapp_id])->where('top_card_expiry', '>=', time())
                    ->column('uid');
                if(!$uidList){
                    $uidList = [-1];
                }
                $where[] = ['a.u_id', 'in', $uidList];
            }
            if ($recommend_tags) {
                $uidList = MemberModel::where(['wxapp_id' => $wxapp_id])->where('recommend_tags', 'like', '%' . $recommend_tags . '%')
                    ->column('uid');
                if(!$uidList){
                    $uidList = [-1];
                }
                $where[] = ['a.u_id', 'in', $uidList];
            }

        }
        if($tags){
            $where[] = ['a.tags', 'like', '%' . $tags . '%'];
        }
        if ($occupation) {
            $where[] = ['a.occupation', '=', $occupation];
        }
        if ($realName) {
            $where[] = ['a.real_name', 'like', '%' . $realName . '%'];
        }
        if ($gender && $gender == '男') {
            $where[] = ['a.gender', '=', 1];
        }
        if ($gender && $gender == '女') {
            $where[] = ['a.gender', '=', 2];
        }
        if (intval($education)>0) {
            $where[] = ['a.education', 'like', '%' . $education . '%'];
        }
        if($maritalStatus){
            if($maritalStatus == '未婚'){
                $maritalStatus = 1;
            }elseif($maritalStatus == '离异'){
                $maritalStatus = 2;
            }elseif ($maritalStatus == '丧偶'){
                $maritalStatus = 3;
            }else{
                $maritalStatus = -1;
            }
            $where[] = ['a.marital_status', '=', $maritalStatus];
        }
        if ($city) {
            $where[] = ['a.city', '=', $city];
        }
        if($province){
            $where[] = ['a.province', '=', $province];
        }

        if(  $this->request->has('is_top')){
              $where[] = ['a.is_top', '=', $is_top];
        }
        if($county){
            $where[] = ['a.county', '=', $county];
        }
        if($keyword){
            $is_top_str='';

            if($this->request->has('is_top')){
                if($matchmaker_id>0) {
                    $where[] = ['a.matchmaker_id', '=', $matchmaker_id];
                    $where[] = ['a.is_top', '=', $is_top];
                    $where2=" a.matchmaker_id ={$matchmaker_id}  and a.is_top={$is_top}";
                }else{
                    $where2=" a.is_top ={$is_top} ";
                }
            }else{
                if($matchmaker_id>0) {
                    $where[] = ['a.matchmaker_id', '=', $matchmaker_id];
                    $where2=" a.matchmaker_id ={$matchmaker_id} ";
                }else{
                    $where2=" 1>0 ";
                }
            }
            if(intval($show_type)==1){
                $where[] = ['a.status', '=', 1];
                $where2.=" and a.status=1";
            }

            $intval_keyword=intval($keyword);
            $where2 .= " and ( a.authentication_id ={$intval_keyword} or a.purchase_status like '%{$keyword}%' or a.vehicle_status like '%{$keyword}%'
                        or a.tags like '%{$keyword}%' or a.occupation like '%{$keyword}%'
                        or a.real_name like  '%$keyword%'  or a.gender like '%{$keyword}%'
                        or a.education like '%{$keyword}%' or a.marital_status like '%{$keyword}%'  or a.city like '%{$keyword}%'
                        or a.county like '%{$keyword}%' or a.income  like '%{$keyword}%'
                        or a.age like '%{$keyword}%'  or a.height like '%{$keyword}%' or a.animal like '%{$keyword}%'
                        or a.have_children  like '%{$keyword} %' or  a.belief like '%{$keyword} %' or notes like '%{$keyword}%'
                        or a.mbti  like '%{$keyword} %' or a.lova_declaration like '%{$keyword} %' or a.real_name like '%{$keyword}%'
                        or a.contact like '%{$keyword}%' or a.nation like  '%{$keyword} %' or a.family_status  like '%{$keyword}%'
                        or a.appearance   like '%{$keyword}%' or a.commitment  like '%{$keyword}%' or a.work like '%{$keyword}%'
                        or a.simple_name  like '%{$keyword}%'  or a.other_describe like '%{$keyword}%'
                         ) 
                        ";
        }
        if($income > 0){

            if($income==1){
                $where[] = ['a.income', '<', 10];
            }elseif ($income==2){
                $where[] = ['a.income', 'between', [10, 15]];
            }elseif ($income==3){
                $where[] = ['a.income', 'between', [16, 20]];
            }elseif ($income==4){
                $where[] = ['a.income', 'between', [20, 50]];
            }elseif ($income==5){
                $where[] = ['a.income', 'between', [50, 100]];
            }elseif ($income==6){
                $where[] = ['a.income', '>', 100];
            }

        }
//        if($age > 0){
//            $where[] = ['a.age', '=', $age];
//        }
        if ($age && $age == '70后') {
            //$where[] = ['a.date_birth', 'like', '197' . '%'];
            $where[] = ['a.age', 'between', [45, 54]];
        }
        if ($age && $age == '80后') {
            //$where[] = ['a.date_birth', 'like', '198' . '%'];
            $where[] = ['a.age', 'between', [35, 44]];
        }
        if ($age && $age == '90后') {
            //$where[] = ['a.date_birth', 'like', '199' . '%'];
            $where[] = ['a.age', 'between', [25, 34]];
        }
        if ($age && $age == '00后') {
            //$where[] = ['a.date_birth', 'like', '200' . '%'];
            $where[] = ['a.age', '<', 25];
        }

        if ($min_height) {
            $where[] = ['a.height', '>=', $min_height];
        }
        if ($max_height) {
            $where[] = ['a.height', '<=', $max_height];
        }
        if($animal){
            $where[] = ['a.animal', '=', $animal];
        }
        if($have_children){
            $where[] = ['a.have_children', '=', $have_children];
        }
        if($belief){
            $where[] = ['a.belief', '=', $belief];
        }

        // 如果红娘id存在，说明是查询红娘旗下的人员
        /*    if ($matchmaker_id) {
                $uidData = MemberModel::where(['wxapp_id' => $wxapp_id, 'matchmaker_id' => $matchmakerId])->column('uid');
                $where[] = ['u_id', 'in', $uidData];
            }*/

        $field   = 'a.status,a.authentication_id,a.photo_auth,a.province,a.parental_status,a.notes,a.matchmaker_id,m.nickname, a.tags, a.contact,a.authentication_id,a.purchase_status,a.income,a.vehicle_status,a.marital_status,a.occupation,a.status,a.age,a.gender,a.education,a.authentication_id,a.head_portrait,a.real_name,a.simple_name,a.date_birth,a.city,a.height,a.weight,a.u_id,a.photos,a.lova_declaration';
        $field="a.*";
        $orderby = 'a.is_top desc';


        if(trim($keyword)){
            $query = ZhAuthenticationModel::alias('a')->leftJoin('member m ', 'm.uid = a.u_id')->where($where2);
        }else{
            $query = ZhAuthenticationModel::alias('a')->leftJoin('member m ', 'm.uid = a.u_id')->where($where);
        }


        if (!$giftNum && !$giveNum) {
            $query = $query->order($orderby);
        }
        if ($giveNum) {
            $field .= ',COUNT(b.collection_id) as coNum';
            $query = $query->leftJoin('zh_collection b ', 'b.release_id = a.u_id')->group('b.release_id')->order('coNum desc');
        }
        if ($giftNum) {
            $field .= ',c.user_id,SUM(c.num) as giftNum';
            $query = $query->leftJoin('zh_give_gift c ', 'c.user_id = a.u_id')->group('a.u_id')->order('giftNum desc');
        }
        $res = $query->field($field)->where('a.wxapp_id', $wxapp_id)->order("a.authentication_id desc")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();


        $res['count']=ZhAuthenticationModel::where(["matchmaker_id"=>$matchmakerId])->count();
        foreach ($res['data'] as &$v) {
//		    $v['head_portrait'] = $this->request->domain() . $v['head_portrait'];
            //$v['age']          = date('Y', time()) - date('Y', strtotime($v['date_birth']));
            $userInfo          = MemberModel::where(['wxapp_id' => $wxapp_id, 'uid' => $v['u_id']])->find();
           // $matchmaker_id = intval($userInfo['matchmaker_id']);
            $matchmaker_id=$v['matchmaker_id'];
            $matchmakerData    = ZhMatchmakerModel::where([
                'matchmaker_id' => $matchmaker_id
            ])->find();
            if($matchmakerData){
                $v['matchmaker'] = [
                    'name'    => $matchmakerData['name'],
                    'remarks' => $matchmakerData['remarks'],
                    'age'     => $matchmakerData['age'],
                    'u_id'    => $matchmakerData['u_id'],
                    'phone' => $matchmakerData['phone']
                ];
            }else{
                $v['matchmaker'] = [
                    'name'    => '',
                    'remarks' => '',
                    'age'     => '',
                    'u_id'    => '',
                    'phone' => ''
                ];
            }


            $isVip             = $userInfo['is_vip'];
            $is_auth           = $userInfo['is_auth'];
            $certify_tags      = empty($userInfo['certify_tags']) ? [] : explode(',', $userInfo['certify_tags']);
            $v['is_vip']       = $isVip;
            $v['is_auth']      = $is_auth;
            $v['certify_tags'] = $certify_tags;
            $ZhCollectionData  = ZhCollectionModel::where(['u_id' => $uid, 'wxapp_id' => $wxapp_id, 'marriage_seeking_id' => $v['authentication_id']])->find();
            if ($ZhCollectionData) {
                $v['is_collection'] = $ZhCollectionData['status'];
            } else {
                $v['is_collection'] = 0;
            }

            if($v['photos']){
                $v['photos'] = json_decode(htmlspecialchars_decode($v['photos']),  true);
            } else {
                $v['photos'] = [$this->request->domain() . '/static/web/img/zhanweitu.png'];
            }


        }
        shuffle($res['data']);
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    function recommend()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId = $this->request->get('uid');
        $limit = $this->request->get('limit', 20, 'intval');
        $page = $this->request->get('page', 1, 'intval');
        $matchmaker_id = $this->request->get('matchmaker_id',0);
        $tags           = $this->request->get('tags', '', 'serach_in');// 小程序 热门专区的标签
//        $uId      = 347;
        $res = ZhAuthenticationModel::where(['wxapp_id' => $wxapp_id, 'u_id' => $uId])->find();

        $o_gender = $res['gender'] == 1 ? 2 : 1;
        $where   = [];
        if($tags){
            $where[] = ['a.tags', 'like', '%' . $tags . '%'];
        }
        // 择偶收入范围
        if (!empty($res['o_income'])) {
            $where[] = ['a.income', '=', $res['o_income']];
        }
        if (intval($res['o_age'])>0) {
            $where[] = ['a.age', '=', $res['o_age']];
        }
        if(doubleval($res['o_min_weight'])>0){
            $where[] = ['a.weight', '>=', $res['o_min_weight']];
        }
        if(doubleval($res['o_max_weight'])>0){
            $where[] = ['a.weight', '<=', $res['o_max_weight']];
        }
        if(doubleval($res['o_weight'])>0){
            $where[] = ['a.weight', '=', $res['o_weight']];
        }
        if(doubleval($res['o_min_height'])>0){
           $where[] = ['a.height', '>=', $res['o_min_height']];
       }
        if(doubleval($res['o_max_height'])>0){
            $where[] = ['a.height', '<=', $res['o_max_height']];
        }
        if(doubleval($res['o_height'])>0){
            $where[] = ['a.height', '=', $res['o_height']];
        }
        if ($res['o_education']!="") {
            $where[] = ['a.education', '=', $res['o_education']];
        }
        if (intval($res['o_child'])>0) {
            $where[] = ['a.have_children', '=', $res['o_child']];
        }
        if(intval($res['o_min_age'])>0){
          $where[] = ['a.age', '>=', $res['o_min_age']];
      }
        if(intval($res['o_max_age'])>0){
            $where[] = ['a.age', '<=', $res['o_max_age']];
        }
        if ($res['o_jg']!="") {
              $where[] = ['a.nation', '=', $res['o_jg']];
        }
         if (intval($res['o_is_drink'])>0) {
             $where[] = ['a.is_drink', '=', $res['o_is_drink']];
         }
         if (intval($res['o_is_smoking'])) {
             $where[] = ['a.is_smoking', '=', $res['o_is_smoking']];
         }
         if(intval($res['o_vehicle_status'])>0){
             $where[] = ['a.vehicle_status', '=', $res['o_vehicle_status']];
         }
        if(intval($res['o_purchase_status'])>0){
            $where[] = ['a.purchase_status', '=', $res['o_purchase_status']];
        }
        if($res['o_nation']){
            $where[] = ['a.nation', '=', $res['o_nation']];
        }
        if($res['o_city']){
            $where[] = ['a.city', '=', $res['o_city']];
        }
         if(intval($res['o_marital_status'])>0){
             $where[] = ['a.marital_status', '=', $res['o_marital_status']];
         }
        if(count($where)>0){
            //红娘身份 不区别性别
            if(intval($matchmaker_id)==0){
                $where[] = ['a.gender', '=', $o_gender];
            }
            $field   = 'a.parental_status,a.matchmaker_id,m.nickname, a.tags,a.contact,a.authentication_id,a.purchase_status,a.income,a.vehicle_status,a.marital_status,a.occupation,a.status,a.age,a.gender,a.education,a.authentication_id,a.head_portrait,a.real_name,a.simple_name,a.date_birth,a.city,a.height,a.weight,a.u_id,a.photos,a.lova_declaration';
            $orderby = 'a.is_top desc';
            $query = ZhAuthenticationModel::alias('a')->leftJoin('member m ', 'm.uid = a.u_id')->where($where);
            $res = $query->field($field)->where('a.wxapp_id', $wxapp_id)->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
            foreach ($res['data'] as &$v) {
                $userInfo          = MemberModel::where(['wxapp_id' => $wxapp_id, 'uid' => $v['u_id']])->find();
                //$matchmaker_id = intval($userInfo['matchmaker_id']);
                $matchmaker_id=$v['matchmaker_id'];
                $matchmakerData    = ZhMatchmakerModel::where([
                    'matchmaker_id' => $matchmaker_id
                ])->find();
                if($matchmakerData){
                    $v['matchmaker'] = [
                        'name'    => $matchmakerData['name'],
                        'remarks' => $matchmakerData['remarks'],
                        'age'     => $matchmakerData['age'],
                        'u_id'    => $matchmakerData['u_id'],
                        'phone' => $matchmakerData['phone']
                    ];
                }else{
                    $v['matchmaker'] = [
                        'name'    => '',
                        'remarks' => '',
                        'age'     => '',
                        'u_id'    => '',
                        'phone' => ''
                    ];
                }
                $isVip             = $userInfo['is_vip'];
                $is_auth           = $userInfo['is_auth'];
               // $tags              = empty($userInfo['tags']) ? [] : explode(',', $userInfo['tags']);
                $certify_tags      = empty($userInfo['certify_tags']) ? [] : explode(',', $userInfo['certify_tags']);
                $v['is_vip']       = $isVip;
              //  $v['tags']         = $tags;
                $v['is_auth']      = $is_auth;
                $v['certify_tags'] = $certify_tags;
                $ZhCollectionData  = ZhCollectionModel::where(['u_id' => $uId, 'wxapp_id' => $wxapp_id, 'marriage_seeking_id' => $v['authentication_id']])->find();
                if ($ZhCollectionData) {
                    $v['is_collection'] = $ZhCollectionData['status'];
                } else {
                    $v['is_collection'] = 0;
                }
                if($v['photos']){
                    $v['photos'] = json_decode(htmlspecialchars_decode($v['photos']),  true);
                } else {
                    $v['photos'] = [$this->request->domain() . '/static/web/img/zhanweitu.png'];
                }


            }
            shuffle($res['data']);
            return $this->ajaxReturn($this->successCode, '返回成功', $res);
        }else{
            return $this->ajaxReturn($this->successCode, '返回成功', '');
        }


    }
    /**
     * 推荐
     * api/ZhAuthentication/recommend
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function recommendold()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->get('uid');
        $limit    = $this->request->get('limit', 20, 'intval');
        $page     = $this->request->get('page', 1, 'intval');
//        $uId      = 347;
        $res = ZhAuthenticationModel::where(['wxapp_id' => $wxapp_id, 'u_id' => $uId])->find();

        // 择偶收入范围
        if (!empty($res['o_income'])) {
            $o_income = explode('-', $res['o_income']);
        }
        // 择偶学历
        $o_education = $res['o_education'];
        // 择偶年龄范围
        if (!empty($res['o_age'])) {
            $o_age = explode(',', $res['o_age']);
        }
        // 择偶身高范围
        if (!empty($res['o_height'])) {
            $o_height = explode(',', $res['o_height']);
        }
        // 择偶体重范围
        if (!empty($res['o_weight'])) {
            $o_weight = explode(',', $res['o_weight']);
        }
        // 择偶婚姻状况
        $o_marital_status = $res['o_marital_status'];
        // 择偶购房情况
        $o_purchase_status = $res['o_purchase_status'];
        // 择偶购车情况
        $o_vehicle_status = $res['o_vehicle_status'];
        // 择偶是否吸烟
        $o_is_smoking = $res['o_is_smoking'];
        // 择偶是否喝酒
        $o_is_drink = $res['o_is_drink'];
        // 择偶民族
        $o_nation = $res['o_nation'];
        // 择偶所在地
        $o_city = $res['o_city'];
        // 择偶性别
        $o_gender = $res['gender'] == 0 ? 1 : 0;



        $where   = [];
        $where[] = ['gender', '=', $o_gender];

        $match_marital_status  = "(CASE WHEN a.marital_status = '{$o_marital_status}' THEN 30 ELSE 0 END)";
        $match_purchase_status = "+(CASE WHEN a.purchase_status = '{$o_purchase_status}' THEN 30 ELSE 0 END)";
        $match_vehicle_status  = "+(CASE WHEN a.vehicle_status = '{$o_vehicle_status}' THEN 30 ELSE 0 END)";
        $match_is_smoking      = "+(CASE WHEN a.is_smoking = '{$o_is_smoking}' THEN 30 ELSE 0 END)";
        $match_is_drink        = "+(CASE WHEN a.is_drink = '{$o_is_drink}' THEN 30 ELSE 0 END)";
        $match_nation          = "+(CASE WHEN a.nation = '{$o_nation}' THEN 30 ELSE 0 END)";
        $match_city            = "+(CASE WHEN a.city = '{$o_city}' THEN 30 ELSE 0 END)";
        $match_education       = "+(CASE WHEN a.education = '{$o_education}' THEN 30 ELSE 0 END)";

        // 信息完整度

        $match_info = "(CASE WHEN a.real_name != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.date_birth != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.city != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.height != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.weight != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.education != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.marital_status != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.have_children != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.contact_type != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.contact != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.nation != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.occupation != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.income != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.purchase_status != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.vehicle_status != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.is_smoking != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.is_drink != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.lova_declaration != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_age != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_height != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_weight != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_education != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_marital_status != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_income != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_nation != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_purchase_status != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_vehicle_status != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_is_smoking != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_is_drink != '' THEN 10 ELSE 0 END)";
        $match_info .= "+(CASE WHEN a.o_remarks != '' THEN 10 ELSE 0 END)";


        if ($o_age) {
            if (count($o_age) > 1) {
                $match_age = "+(CASE WHEN YEAR(CURDATE()) - YEAR(date_birth) - (RIGHT(CURDATE(), 5) < RIGHT(date_birth, 5)) >=  {$o_age[0]} AND YEAR(CURDATE()) - YEAR(date_birth) - (RIGHT(CURDATE(), 5) < RIGHT(date_birth, 5)) <= {$o_age[1]} THEN 30 ELSE 0 END)";
            } else {
                $match_age = "+(CASE WHEN YEAR(CURDATE()) - YEAR(date_birth) - (RIGHT(CURDATE(), 5) < RIGHT(date_birth, 5)) >= {$o_age[0]} THEN 30 ELSE 0 END)";
            }
        } else {
            $match_age = "";
        }
        if ($o_income) {
            if (count($o_income) > 1) {
                $match_income = "+(CASE WHEN a.income >= {$o_income[0]} AND a.income <= {$o_income[1]} THEN 30 ELSE 0 END)";
            } else {
                $match_income = "+(CASE WHEN a.income >= {$o_income[0]} THEN 30 ELSE 0 END)";
            }
        } else {
            $match_income = "";
        }

        if ($o_height) {
            if (count($o_height) > 1) {
                $match_height = "+(CASE WHEN a.height >= {$o_height[0]} AND a.height <= {$o_height[1]} THEN 30 ELSE 0 END)";
            } else {
                $match_height = "+(CASE WHEN a.height >= {$o_height[0]} THEN 30 ELSE 0 END)";
            }
        } else {
            $match_height = "";
        }

        if ($o_weight) {
            if (count($o_weight) > 1) {
                $match_weight = "+(CASE WHEN a.weight >= {$o_weight[0]} AND a.weight <= {$o_weight[1]} THEN 30 ELSE 0 END)";
            } else {
                $match_weight = "+(CASE WHEN a.weight >= {$o_weight[0]} THEN 30 ELSE 0 END)";
            }
        } else {
            $match_weight = "";
        }

        $match_score = "({$match_marital_status} {$match_purchase_status} {$match_vehicle_status} {$match_is_smoking} {$match_is_drink} {$match_nation} {$match_city} {$match_age} {$match_education} {$match_income} {$match_height} {$match_weight})";
        $match_info  = "({$match_info}) as match_info";
//        /360*100

        $field = 'a.authentication_id,a.head_portrait,a.real_name,a.date_birth,a.city,a.height,a.weight,a.u_id,a.photos,a.lova_declaration,' . $match_score . ' as match_score,' . $match_info;
        $query = ZhAuthenticationModel::alias('a')->where($where);
        $query->whereRaw($match_score . '>0');
        $query->order('match_score desc');
        $res = $query->field($field)->where('a.wxapp_id', $wxapp_id)->paginate(['list_rows' => $limit, 'page' => $page])->toArray();


        // 如果没有匹配的，返回信息完整度最高的6位
   /*     if (empty($res['data']) && $page == 1) {
            $field = 'a.authentication_id,a.head_portrait,a.real_name,a.date_birth,a.city,a.height,a.weight,a.u_id,a.photos,a.lova_declaration,' . $match_score . ' as match_score,' . $match_info;
            $query = ZhAuthenticationModel::alias('a')->where($where);
            $query->order('match_score desc,match_info desc');
            $res = $query->field($field)->where('a.wxapp_id', $wxapp_id)->paginate(['list_rows' => 6, 'page' => $page])->toArray();
        }*/

        $tmpUids = [];
        foreach ($res['data'] as $v) {
            $tmpUids[] = $v['u_id'];
        }
        $nicknameList = [];
        if(! empty($tmpUids)){
            $nicknameList = MemberModel::whereIn('uid', $tmpUids)->column('nickname', 'uid');
        }

        foreach ($res['data'] as &$v) {
            $v['real_name'] = $nicknameList[$v['u_id']] ?? '';
            $v['age']          = date('Y', time()) - date('Y', strtotime($v['date_birth']));
            $userInfo          = MemberModel::where(['wxapp_id' => $wxapp_id, 'uid' => $v['u_id']])->find();
            $isVip             = $userInfo['is_vip'];
            $tags              = empty($userInfo['tags']) ? [] : explode(',', $userInfo['tags']);
            $certify_tags      = empty($userInfo['certify_tags']) ? [] : explode(',', $userInfo['certify_tags']);
            $v['is_vip']       = $isVip;
            $v['tags']         = $tags;
            $v['certify_tags'] = $certify_tags;
            $ZhCollectionData  = ZhCollectionModel::where(['u_id' => $uId, 'wxapp_id' => $wxapp_id, 'marriage_seeking_id' => $v['authentication_id']])->find();
            if ($ZhCollectionData) {
                $v['is_collection'] = $ZhCollectionData['status'];
            } else {
                $v['is_collection'] = 0;
            }

            if ($v['photos']) {
                $v['photos'] = explode(',', $v['photos']);
            } else {
                $v['photos'] = $this->request->domain() . '/static/web/img/zhanweitu.png';
                $v['photos'] = explode(',', $v['photos']);
            }


            $v['match_score'] = round($v['match_score'] / 360 * 100, 2);
            $v['match_info']  = round($v['match_info'] / 300 * 100, 2);

        }
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    /**
     * @api             {get} /ZhAuthentication/view 02、查看详情
     * @apiGroup        ZhAuthentication
     * @apiVersion      1.0.0
     * @apiDescription  查看详情
     * @apiParam (输入参数：) {string}            authentication_id 主键ID
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据详情
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":"201","msg":"没有数据"}
     */
    function view()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $authentication_id=$this->request->get('authentication_id');
        $u_id=$this->request->get('u_id');
        $show_type=$this->request->get('show_type');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        // 获取用户id 用以判断用户是否登录
        $token = $this->request->header('Authorization');
        $uid   = 0;
        if ($token) {
            $jwt = Jwt::getInstance();
            $jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))
                ->setSecrect(config('my.jwt_secrect'))
                ->setToken($token);
            $uid  = $jwt->decode()->getClaim('uid');
            $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
            if (!$user) {
                return $this->ajaxReturn($this->errorCode, '未知用户');
            }
        }
        // $uid = 349;

        $data['authentication_id'] = $authentication_id;
        $data['wxapp_id']          = $wxapp_id;
        //$data['status']          = 1;
        $datas  = [
            'wxapp_id' => $wxapp_id,
            'u_id'     => $uid,
        ];
        $matchmaker   = ZhMatchmakerModel::where($datas)->find();
        $matchmaker_id=0;
        if($matchmaker){
            $matchmaker_id=$matchmaker["matchmaker_id"];
        }

        //判断查询的佳人是当前红娘自己的，则不筛选状态
        if(intval($show_type)==1){
            $data['status']          = 1;
        }

        // $field                     = 'authentication_id,head_portrait,real_name,gender,date_birth,city,height,weight,education,marital_status,have_children,contact_type,contact,wechat,nation,occupation,photos,income,purchase_status,vehicle_status,is_smoking,is_drink,lova_declaration,o_age,o_height,o_city,o_weight,o_education,o_marital_status,o_income,o_nation,o_purchase_status,o_vehicle_status,o_is_smoking,o_is_drink,o_remarks,u_id,wxapp_id,createtime,family_status';
        $res                       = checkData(ZhAuthenticationModel::field("*")->where($data)->find());
        //当前佳人的红娘id
        $au_m_id=intval($res['matchmaker_id']);
        if(empty($res)){
            return $this->ajaxReturn($this->successCode, '没有佳人数据',    '');
        }
        $a_uid=$res["u_id"];
        //查询自己的佳人信息，不用判断status
       /* if($a_uid!=$u_id||$au_m_id!=$matchmaker_id){
            if(intval( $res['status'])!=1){
                return $this->ajaxReturn($this->successCode, '佳人数据待审核',    '');
            }
        }*/
        //格式化学历
        $matchmakerData    = ZhMatchmakerModel::where([
            'matchmaker_id' => $res['matchmaker_id']
        ])->find();
        if($matchmakerData){
            $res['matchmaker'] = [
                'name'    => $matchmakerData['name'],
                'remarks' => $matchmakerData['remarks'],
                'age'     => $matchmakerData['age'],
                'u_id'    => $matchmakerData['u_id'],
                'phone' => $matchmakerData['phone']
            ];
        }else{
            $res['matchmaker'] = [
                'name'    => '',
                'remarks' => '',
                'age'     => '',
                'u_id'    => '',
                'phone' => '',
            ];
        }

        if($res['u_id'] > 0){
            $memberData   = MemberModel::where(['wxapp_id' => $wxapp_id, 'uid' => $res['u_id']])->find();
            $isVip        = $memberData['is_vip'];
            $phone        = $memberData['phone'];
            $avatar       = $memberData['avatar'];
            $is_auth      = $memberData['is_auth'];
            $tags         = $memberData['tags'];
            $certify_tags = $memberData['certify_tags'];
        }else{
            $isVip = 0;
            $phone = "";
            $avatar = "";
            $is_auth = 0;
            $tags = "";
            $certify_tags = "" ;
        }


        $tags         = empty($tags) ? [] : explode(',', $tags);
        $certify_tags = empty($certify_tags) ? [] : explode(',', $certify_tags);

        $matchmaker_id = $memberData['matchmaker_id'];
        if (empty($matchmaker_id)) {
            // 公共红娘
            $matchmaker_id = 27;
        }
        //获取佳人是否缴纳保证金
        $matchmaker_order=\app\api\model\ZhMatchmakerOrder::where(["a_id"=>$authentication_id,"status"=>1,"c_id"=>16])->find();
        if($matchmaker_order){
            $res['is_bond'] = 1;
        }else{
            $res['is_bond'] = 0;
        }


        $res['matchmaker_id'] = $matchmaker_id;
        $res['is_vip']        = $isVip;
        $res['is_auth']       = $is_auth;
        $res['tags']          = $tags;
        $res['certify_tags']  = $certify_tags;·.
        $res['avatar']        = $avatar;
        //$res['age']           = date('Y', time()) - date('Y', strtotime($res['date_birth']));

        //$maritalStatus         = ["", '未婚', '离异', '丧偶']; //原样返回给前端
        //$res['marital_status'] = $maritalStatus[$res['marital_status']];
        $res['o_age']          = str_ireplace(',', '~', $res['o_age']);
        $res['o_height']       = str_ireplace(',', '~', $res['o_height']);
        $res['o_weight']       = str_ireplace(',', '~', $res['o_weight']);
        $res['phone']          = $phone;

        if (!empty($uid)) {
            $exchangeData  = \app\api\model\ZhExchange::where([
                'u_id'         => $uid,
                'wxapp_id'     => $wxapp_id,
                'exchange_uid' => $res['u_id'],
                'status'       => 1
            ])->find();
            $exchangeData2 = \app\api\model\ZhExchange::where([
                'u_id'         => $res['u_id'],
                'wxapp_id'     => $wxapp_id,
                'exchange_uid' => $uid,
                'status'       => 1
            ])->find();
            if (empty($exchangeData) && empty($exchangeData2)) {
                $res['phone']       = '';
                $res['contact']     = '';
                $res['wechat']      = '';
                $res['is_exchange'] = 0;
            } else {
                $res['is_exchange'] = 1;
            }
        } else {
            $res['is_exchange'] = 0;
            $res['phone']       = '';
            $res['contact']     = '';
            $res['wechat']      = '';
        }
//        $res['head_portrait'] = $this->request->domain() . $res['head_portrait'];

        /*   if ($res['photos']) {
               $res['photos'] = explode(',', $res['photos']);
   //            foreach ($res['photos'] as &$v){
   //                $v = $this->request->domain() . $v;
   //            }
           } else {
               $res['photos'] = $this->request->domain() . '/static/web/img/zhanweitu.png';
               $res['photos'] = explode(',', $res['photos']);
           }*/

        $res['photos'] = json_decode(htmlspecialchars_decode( $res['photos']),  true);
        $res['videos'] = json_decode(htmlspecialchars_decode( $res['videos']),  true);

        if($res["o_education"]=="0"){
            $res["o_education"]=["0"];
        }else{
            $res["o_education"]=explode(",", $res["o_education"]);
        }

        if( $res["o_marital_status"]=="0"){
            $res["o_marital_status"]=["0"];
        }else{
            $res["o_marital_status"]=explode(",", $res["o_marital_status"]);
        }
        unset($v);
        $ZhCollectionData = ZhCollectionModel::where(['u_id' => $uid, 'wxapp_id' => $wxapp_id, 'marriage_seeking_id' => $res['authentication_id']])->find();
        if ($ZhCollectionData) {
            $res['is_collection'] = $ZhCollectionData['status'];
        } else {
            $res['is_collection'] = 0;
        }
        $fields = ['have_children', 'sex', 'self_bulit', 'purchase_status', 'vehicle_status' , 'is_smoking', 'is_drink', 'o_child', 'o_vehicle_status', 'o_is_smoking', 'o_is_drink'];
        foreach($fields as $f){
            if(isset($res[$f])){
                $res[$f] = intval($res[$f]);
            }
        }
        return $this->ajaxReturn($this->successCode, '返回成功', $res ?: '');
    }

    /**
     * @api             {post} /ZhAuthentication/add 03、添加
     * @apiGroup        ZhAuthentication
     * @apiVersion      1.0.0
     * @apiDescription  添加
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (输入参数：) {string}            head_portrait 头像 (必填)
     * @apiParam (输入参数：) {string}            real_name 真实姓名 (必填)
     * @apiParam (输入参数：) {int}                gender 性别 男|1|success,女|0|warning
     * @apiParam (输入参数：) {string}            date_birth 出生日期 (必填)
     * @apiParam (输入参数：) {string}            city 所在地城市 (必填)
     * @apiParam (输入参数：) {string}            height 身高 (必填)
     * @apiParam (输入参数：) {string}            weight 体重 (必填)
     * @apiParam (输入参数：) {string}            education 学历 (必填)
     * @apiParam (输入参数：) {int}                marital_status 婚姻状况 (必填) 未婚|0|success,离婚|1|warning,离异|2|primary ,丧偶|4|info
     * @apiParam (输入参数：) {int}                have_children 有无子女 有|1|success,没有|0|warning
     * @apiParam (输入参数：) {string}            contact_type 联系方式 (必填)
     * @apiParam (输入参数：) {string}            contact 联系号码 (必填)
     * @apiParam (输入参数：) {string}            nation 民族 (必填)
     * @apiParam (输入参数：) {string}            occupation 职业 (必填)
     * @apiParam (输入参数：) {string}            photos 照片
     * @apiParam (输入参数：) {string}            income 月收入 (必填)
     * @apiParam (输入参数：) {int}                purchase_status 购房情况 (必填) 已购房|0|success,和家人同住|1|warning,租房|2|primary,婚后买房|3|info
     * @apiParam (输入参数：) {int}                vehicle_status 购车情况 (必填) 已购车|1|success,未购车|0|warning
     * @apiParam (输入参数：) {int}                is_smoking 是否抽烟 (必填) 是|1|success,否|0|warning
     * @apiParam (输入参数：) {int}                is_drink 是否喝酒 (必填) 是|1|success,否|0|warning
     * @apiParam (输入参数：) {string}            lova_declaration 爱情宣言
     * @apiParam (输入参数：) {string}            o_age 择偶年龄 (必填)
     * @apiParam (输入参数：) {string}            o_height 择偶身高 (必填)
     * @apiParam (输入参数：) {string}            o_city 择偶所在地 (必填)
     * @apiParam (输入参数：) {string}            o_weight 择偶体重 (必填)
     * @apiParam (输入参数：) {string}            o_education 择偶学历 (必填)
     * @apiParam (输入参数：) {int}                o_marital_status 择偶婚况 (必填) 未婚|0|success,离婚|1|warning,离异|2|primary ,丧偶|4|info
     * @apiParam (输入参数：) {string}            o_income 择偶月收入 (必填)
     * @apiParam (输入参数：) {string}            o_nation 择偶民族 (必填)
     * @apiParam (输入参数：) {int}                o_purchase_status 择偶购房情况 (必填) 已购房|0|success,和家人同住|1|warning,租房|2|primary,婚后买房|3|info
     * @apiParam (输入参数：) {int}                o_vehicle_status 择偶购车情况 (必填) 已购车|1|success,未购车|0|warning
     * @apiParam (输入参数：) {int}                o_is_smoking 择偶是否吸烟 (必填) 是|1|success,否|0|warning
     * @apiParam (输入参数：) {int}                o_is_drink 择偶是否喝酒 (必填) 是|1|success,否|0|warning
     * @apiParam (输入参数：) {string}            o_remarks 我的理想型
     * @apiParam (输入参数：) {int}                u_id 用户id
     * @apiParam (输入参数：) {string}            wxapp_id 平台id
     * @apiParam (输入参数：) {int}                release_type 发布类型 (必填) 红娘|1|success,个人|0|warning
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码  201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.msg 返回成功消息
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":"操作成功"}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"操作失败"}
     */
    function add()
    {
        $traceIds = []; //微信图片安全审核用的traceId
        $wxapp_id = $this->request->post('wxapp_id');
        $uId = $this->request->uid; //从中间件中获取uid
        //$uId      = $this->request->post('uid'); //当前用户的ID
        $type     = $this->request->post('type'); //操作的类型，资料项还是其它的
        $userType = $this->request->post('user_type', '', 'serach_in'); //当前用户的类型 红娘还是佳人 1佳人 2红娘今天
        $zhPhone  = $this->request->post('zhphone', '', 'serach_in'); //佳人的电话号码，用于创建会员表，新逻辑中没有用了
        $authentication_id=$this->request->post('authentication_id',0); //资料ID，用于区分新增还是修改
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        //照片权限 1公开 2私密
        if($this->request->has('photo_auth')){
            $data['photo_auth']     = $this->request->post('photo_auth');
        }
        if($this->request->has('address')){
            $data['address']     = $this->request->post('address');
        }

          if($this->request->has('other_describe')){
              $data['other_describe']     = $this->request->post('other_describe');
          }
        if($this->request->has('o_child')){
            $data['o_child']     = $this->request->post('o_child');
        }
        if($this->request->has('work')){
            $data['work']     = $this->request->post('work');
        }
        if($this->request->has('self_built')){
            $data['self_built']     = $this->request->post('self_built');
        }
        if($this->request->has('age')){
            $data['age']     = $this->request->post('age');
        }
        if($this->request->has('notes')){
            $data['notes']     = $this->request->post('notes');
        }
        if($this->request->has('date_birth')){
            $data['date_birth']     = $this->request->post('date_birth');
        }
        if($this->request->has('matchmaker_id')){
            $data['matchmaker_id']     = $this->request->post('matchmaker_id');
        }
        if($this->request->has('u_id')){
            $data['u_id']     = $this->request->post('u_id');
        }
        if($this->request->has('authentication_id')){
            $data['authentication_id']     = $this->request->post('authentication_id');
        }
        if($this->request->has('head_portrait')){
            $data['head_portrait']     = $this->request->post('head_portrait');
        }
        if($this->request->has('real_name')){
            $data['real_name']     = $this->request->post('real_name');
        }
        //性别字段，红娘修改佳人与自己修改佳人页面，前端原先不统一，作了兼容
        if($this->request->has('gender')){
            $data['gender']     = $this->request->post('gender');
        }
        if($this->request->has('sex')){
            $data['gender']     = $this->request->post('sex');
        }
        if($this->request->has('date_birth')){
            $data['date_birth']     = $this->request->post('date_birth');
        }
        //省份
        if($this->request->has('province')){
            $data['province']     = $this->request->post('province');
        }
        //县区
        if($this->request->has('county')){
            $data['county']     = $this->request->post('county');
        }
        //作废
        if($this->request->has('area')){
            $data['area']     = $this->request->post('area');
        }
        if($this->request->has('city')){
            $data['city']     = $this->request->post('city');
        }
        if($this->request->has('height')){
            $data['height']     = $this->request->post('height');
        }
        if($this->request->has('weight')){
            $data['weight']     = $this->request->post('weight');
        }
        if($this->request->has('photos')){
            $data['photos']     = $this->request->post('photos');
        }
        if($this->request->has('user_type')){
            $data['user_type']     = $this->request->post('user_type');
        }
        if($this->request->has('simple_name')){
            $data['simple_name']     = $this->request->post('simple_name');
        }
        if($this->request->has('is_party_member')){
            $data['is_party_member']     = $this->request->post('is_party_member');
        }
        if($this->request->has('mbti')){
            $data['mbti']     = $this->request->post('mbti');
        }
        if($this->request->has('constellation')){
            $data['constellation']     = $this->request->post('constellation');
        }
        if($this->request->has('tags')){
            $data['tags']     = $this->request->post('tags');
        }
        if($this->request->has('o_age')){
            $data['o_age']     = $this->request->post('o_age');
        }
        if($this->request->has('o_height')){
            $data['o_height']     = $this->request->post('o_height');
        }
        if($this->request->has('o_city')){
            $data['o_city']     = $this->request->post('o_city');
        }
        if($this->request->has('o_weight')){
            $data['o_weight']     = $this->request->post('o_weight');
        }
        if($this->request->has('o_education')){
            $data['o_education']     = $this->request->post('o_education');
        }
        if($this->request->has('o_marital_status')){
            $data['o_marital_status']     = $this->request->post('o_marital_status');
        }
        if($this->request->has("o_jg")){
            $data['o_jg']     = $this->request->post('o_jg');
        }
        if($this->request->has('animal')){
            $data['animal']     = $this->request->post('animal');
        }
        if($this->request->has('appearance')){
            $data['appearance']     = $this->request->post('appearance');
        }
        if($this->request->has('belief')){
            $data['belief']     = $this->request->post('belief');
        }

        if($this->request->has('parental_status')){
            $data['parental_status']     = $this->request->post('parental_status');
        }
        if($this->request->has('sibling')){
            $data['sibling']     = $this->request->post('sibling');
        }
        if($this->request->has('zodiac_clash')){
            $data['zodiac_clash']     = $this->request->post('zodiac_clash');
        }
        if($this->request->has('commitment')){
        $data['commitment']     = $this->request->post('commitment');
          }
        if($this->request->has('contacts')){
            $data['contacts']     = $this->request->post('contacts');
        }
        if($this->request->has('is_smoking')){
            $data['is_smoking']     = $this->request->post('is_smoking');
        }
        if($this->request->has('is_drink')){
            $data['is_drink']     = $this->request->post('is_drink');
        }
        if($this->request->has('vehicle_status')){
             $data['vehicle_status']     = $this->request->post('vehicle_status');
         }
        if($this->request->has('lova_declaration')){
             $data['lova_declaration']     = $this->request->post('lova_declaration');
         }
          if($this->request->has('o_min_age')){
            $data['o_min_age']     = $this->request->post('o_min_age');
        }
        if($this->request->has('o_max_age')){
            $data['o_max_age']     = $this->request->post('o_max_age');
        }
        if($this->request->has('o_min_height')){
            $data['o_min_height']     = $this->request->post('o_min_height');
        }
        if($this->request->has('o_max_height')){
            $data['o_max_height']     = $this->request->post('o_max_height');
        }
        if($this->request->has('education')){
            $data['education']     = $this->request->post('education');
        }
        if($this->request->has('nation')){
            $data['nation']     = $this->request->post('nation');
        }
        if($this->request->has('occupation')){
            $data['occupation']     = $this->request->post('occupation');
        }
        if($this->request->has('family_status')){
            $data['family_status']     = $this->request->post('family_status');
        }
        if($this->request->has('o_income')){
            $data['o_income']     = $this->request->post('o_income');
        }
        if($this->request->has('o_nation')){
            $data['o_nation']     = $this->request->post('o_nation');
        }
        if($this->request->has('income')){
            $data['income']     = $this->request->post('income');
        }
        if($this->request->has('o_remarks')){
            $data['o_remarks']     = $this->request->post('o_remarks');
        }
        if($this->request->has('o_is_drink')){
            $data['o_is_drink']     = $this->request->post('o_is_drink');
        }
        if($this->request->has('o_is_smoking')){
            $data['o_is_smoking']     = $this->request->post('o_is_smoking');
        }
        if($this->request->has('o_vehicle_status')){
            $data['o_vehicle_status']     = $this->request->post('o_vehicle_status');
        }
        if($this->request->has('o_purchase_status')){
            $data['o_purchase_status']     = $this->request->post('o_purchase_status');
        }

        if($this->request->has('purchase_status')){
            $data['purchase_status']     = $this->request->post('purchase_status');
        }
        if($this->request->has('head_portrait')){
            $data['head_portrait']     = $this->request->post('head_portrait');
        }
        if($this->request->has('real_name')){
            $data['real_name']     = $this->request->post('real_name');
        }
        if($this->request->has('marital_status')){
            $data['marital_status']     =  $this->request->post('marital_status', 0);
            //$data['marital_status']     =  $this->request->post('marital_status') == '未婚' ? 0 : ($this->request->post('marital_status') == '离异' ? 1 : 2);
        }
        if($this->request->has('have_children')){
            $data['have_children']     = $this->request->post('have_children');// == '无' ? 0 : 1;
        }
        if($this->request->has('contact_type')){
            $data['contact_type']     = $this->request->post('contact_type') == 1 ? '微信' : ($this->request->post('contact_type') == 2 ? 'QQ' : '电话');
        }
        if($this->request->has('photos')){
            $data['photos']     = $this->request->post('photos');
        }
        if($this->request->has('videos')){
            $data['videos']     = $this->request->post('videos');
        }

        //照片，线上版本逗号隔开，体验版传数组
        if(isset($data['photos']) && ! empty($data['photos'])){
            if(is_array($data['photos'])){
                $data['photos'] = json_encode($data['photos']);
            }else{
                $data['photos'] = json_encode(explode(",", $data['photos']));
            }
        }
        //视频，线上版本逗号隔开，体验版传数组
        if(isset($data['videos']) && ! empty($data['videos'])){
            if(is_array($data['videos'])){
                $data['videos'] = json_encode($data['videos']);
            }else{
                $data['videos'] = json_encode(explode(",", $data['videos']));
            }
        }

     /*   $data["o_education"]=implode(",", $data["o_education"]);
        $data["o_marital_status"]=implode(",", $data["o_marital_status"]);*/

        if($this->request->has('o_min_weight')){
            $data['o_min_weight']     = $this->request->post('o_min_weight');
        }
        if($this->request->has('o_max_weight')){
            $data['o_max_weight']     = $this->request->post('o_max_weight');
        }
        if($this->request->has('o_other')){
            $data['o_other']     = $this->request->post('o_other');
        }

        //提交微信审核需要openid, 取当前用户的
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        //微信合规字符校验
        //读取用户信息，微信文本安全和图片安全的时候，需要校验，只有佳人身份的时候需要校验
      /*  try{
            //文字信息，合规校验
            $this->wechatTextCheck($data, $wxSetting, $user['openid']);
        } catch (\Exception $e) {
            file_put_contents('jiaren_debug', $user['openid'] .','. $e->getMessage().','. json_encode($data));
            //return $this->ajaxReturn($this->errorCode, $e->getMessage(). ','. $checkContent); //调试的时候使用
            return $this->ajaxReturn($this->errorCode, '您提交的信息涉及违规，请修改！');
        }*/
        //微信图片验证
  /*      if($type == 2){
            //如果有资料ID，先查询次料的信息
            $ZhAuthenticationData = [];
            if($authentication_id > 0){
                $ZhAuthenticationData = ZhAuthenticationModel::where(['wxapp_id' => $wxapp_id, 'authentication_id' => $authentication_id])->find();
            }
            $traceIds = $this->wechatPicCheck($data, $ZhAuthenticationData, $wxSetting, $uId, $user['openid']);
        }*/
        //每次的资料修改，都是设为待审核，一定要后台审核通过，才展示
        $data['status']        = 0;

        //基础信息
        if ($type == 1) {
            if ($userType == 2) {
                $data['release_type']  = 1; // 发布类型 1红娘 0个人
                //$data['matchmaker_id'] = $matchmaker_id;  // 所属红娘id
                /* 红娘发布佳人的逻辑，根据手机号创建用户
                if (!$zhPhone) {
                    return $this->ajaxReturn($this->errorCode, '缺少注册电话');
                }
                $MemberData = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $zhPhone])->find();
                if ($MemberData) {
                    return $this->ajaxReturn($this->errorCode, '该手机号已绑定用户，请重新发布');
                } else {
                    $memberId = MemberModel::insertGetId([
                        'wxapp_id'      => $wxapp_id,
                        'phone'         => $zhPhone,
                        'real_name'     => $data['real_name'],
                        'create_time'   => time(),
                        'matchmaker_id' => $uId
                    ]);
                    if ($memberId) {//这逻辑混乱，不需要赋值
                        //$uId = $memberId;
                    } else {
                        return $this->ajaxReturn($this->errorCode, '发布失败，请稍后重试');
                    }
                }*/

            } elseif ($userType == 1) {//这里是个人发布
                if ($authentication_id == 0) {//首次新增资料的时候
                    $data['release_type'] = 0; // 发布类型 1红娘 0个人
                }
                //佳人输入了真实姓名，同步修改会员表的真实姓名与性别
                if (isset($data['real_name'])) {
                    //会员的姓名
                    MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])
                        ->update([
//                                   'real_name'=> $data['real_name'],
                            'sex' => $data['gender']
                        ]);
                }
            }
        }

//        $data['videos']               = htmlspecialchars_decode($this->request->post('videos')); //5.21注释这行，前面已经处理了
        //&& $userType != 2
        //有资料ID，只做更新
        if ($authentication_id > 0) {
            //添加记录红娘id，如果是自己的红娘ID为0
            $data['matchmaker_id']=$this->request->post('matchmaker_id', 0);
            $res = ZhAuthenticationModel::where('authentication_id', $authentication_id)->update($data);
        } else {
            $data['wxapp_id']   = $wxapp_id;
            if($userType == 1){
                $data['u_id']       = $uId;
            }
            $data['createtime'] = time();
            $res                = ZhAuthenticationService::add($data);
            $authentication_id = $res;
        }
        //有微信审核记录，根据微信返回的trace_id更新资料ID
      /*  if(! empty($traceIds)){
            ZhWechatMediaLog::whereIn('trace_id', $traceIds)->update(['authentication_id' => $authentication_id]);
        }*/
        return $this->ajaxReturn($this->successCode, '操作成功', $res);
    }

    //微信文本检查
    private function wechatTextCheck($data, $wxSetting, $openid){
        $checkContent = "";
       // $field = ['real_name', 'notes','work', 'nation', 'occupation','family_status','appearance', 'belief', 'parental_status', 'sibling', 'zodiac_clash', 'commitment','contacts','lova_declaration', 'o_nation', 'o_remarks', 'o_other'];
        $field=['simple_name'];
        $tmp = [];
        foreach ($field as $f){
            if(!empty(trim($data[$f]))){
                $tmp[] = trim($data[$f]);
            }
        }
        if(! empty($tmp)){
            $checkContent = implode(',', $tmp);
        }
        if(! empty($checkContent)) {
            //有问题，抛出异常，外层补捕
            MsgSecCheck::checkText($wxSetting['app_id'], $wxSetting['app_secret'], $openid, $checkContent);
        }
    }

    //微信图片审核, 返回traceId 数组
    private function wechatPicCheck($data, $ZhAuthenticationData, $wxSetting, $uId, $openid){
        $traceIds = [];
        $newPhotos = [];
        $headPortrait = "";
        if(isset($data['head_portrait']) && trim($data['head_portrait']) != ''){
            $headPortrait = trim( $data['head_portrait']);
        }
        if(! empty($headPortrait)){
            $newPhotos[] = $headPortrait;
        }
        $photos = $data['photos'] ?? [];
        if(! empty($photos)){
            $newPhotos = array_merge($newPhotos, json_decode($photos, true));
        }
        if(! empty($ZhAuthenticationData)){//已有资料，已添加的图片，不用重新发起审核
            $existPhotos = [];
            if(trim($ZhAuthenticationData['head_portrait']) != ""){
                $existPhotos[] = trim($ZhAuthenticationData['head_portrait']);
            }
            if(trim($ZhAuthenticationData['photos']) != ""){
                $tmpPhotos = json_decode(trim($ZhAuthenticationData['photos']), true);
                $existPhotos = array_merge($existPhotos, $tmpPhotos);
            }
            $newPhotos = array_diff($newPhotos, $existPhotos);
            $existPhotos = null;
        }
        //如果有未审核的照片
        if(! empty($newPhotos)){
            foreach($newPhotos as $photo){//没有资料，新增
                //这里只提交，不抛异常
                $traceIds[] = MediaCheckAsync::checkMedia($wxSetting['app_id'], $wxSetting['app_secret'], $uId, $openid, 2, $photo);
            }
        }
        return $traceIds;
    }

    // 获取用户是否已完善信息
    function getMyReleaseData()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $uId      = $this->request->get('uid');
        if (!$uId) {
            return $this->ajaxReturn($this->errorCode, '缺少用户参数');
        }
        $res      = ZhAuthenticationModel::where(['wxapp_id' => $wxapp_id, 'u_id' => $uId])->find();
        $res['photos'] = json_decode(htmlspecialchars_decode( $res['photos']), true);
        $res['videos'] = json_decode(htmlspecialchars_decode( $res['videos']), true);

        if( $res["o_education"]=="0"){
            $res["o_education"]=["0"];
        }else{
            $res["o_education"]=explode(",", $res["o_education"]);
        }

        /**
        有无子女 have_children： 1无 2有
        性别 sex 1男 2女
        自建房 self_bulit 1无 2有
        购房情况 purchase_status 1无 2一套 3两套 4三套以上 5婚后买房
        购车情况 vehicle_status 1未购车2一辆车3多辆车
        详细资料：
        是否吸烟 is_smoking 1不吸烟 2吸烟
        是否喝酒 is_drink  1不喝酒 2喝酒
        择偶资料：
        择偶有无小孩 o_child 1无 2有
        购房情况 o_purchase_status 1无 2一套 3两套 4三套以上 5婚后买房
        购车情况 o_vehicle_status  1未购车 2已购车
        是否吸烟o_is_smoking  1不吸烟 2吸烟
        是否喝酒o_is_drink 1不喝酒 2喝酒
         */
        $fields = ['have_children', 'sex', 'self_bulit', 'purchase_status', 'vehicle_status' , 'is_smoking', 'is_drink', 'o_child', 'o_purchase_status', 'o_vehicle_status', 'o_is_smoking', 'o_is_drink'];
        foreach($fields as $f){
            if(isset($res[$f])){
               $res[$f] = intval($res[$f]);
            }
        }
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }


    // 修改发布信息显示隐藏
    function editShow()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        $isShow   = $this->request->post('is_show', '', 'serach_in');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }
        $data = ZhAuthenticationModel::where(['wxapp_id' => $wxapp_id, 'u_id' => $uId])->find();
        if ($data) {
            $res = ZhAuthenticationModel::where([
                'wxapp_id'          => $wxapp_id,
                'u_id'              => $uId,
                'authentication_id' => $data['authentication_id']
            ])->update(['is_show' => $isShow]);
            return $this->ajaxReturn($this->successCode, '修改成功');
        }
        return $this->ajaxReturn($this->errorCode, '修改失败');
    }


    //删除佳人
    function delete(){
        $authentication_id  = intval($this->request->post('authentication_id'));
        /* $data=[];
         $data['matchmaker_id']=0;
         $res = ZhAuthenticationModel::where('authentication_id',$authentication_id)->update($data);*/
        if($authentication_id<=0){
            return $this->ajaxReturn($this->errorCode, '请传递正确的佳人id');
        }
        //直接删除佳人信息
        $res = ZhAuthenticationModel::where('authentication_id',$authentication_id)->delete();

        if($res){
            return $this->ajaxReturn($this->successCode, '删除成功');
        }else{
            return $this->ajaxReturn($this->errorCode, '删除失败');
        }

    }
    //红娘删除佳人
    function matchmaker_del(){
        $authentication_id  = intval($this->request->post('authentication_id'));
        $matchmaker_id=$this->request->post('matchmaker_id');
        $res = ZhAuthenticationModel::where(['authentication_id'=>$authentication_id,"matchmaker_id"=>$matchmaker_id])->update(["matchmaker_id"=>0]);
        if($res){
            return $this->ajaxReturn($this->successCode, '解绑佳人成功');
        }else{
            return $this->ajaxReturn($this->errorCode, '解绑佳人失败');
        }
    }

    //获取系统配置 对应后台的小程序设置信息
    function gettel(){
        $wxapp_id = $this->request->get('wxapp_id');
        $res = ZhTel::where(['wxapp_id'=>$wxapp_id])->find();
        return $this->ajaxReturn($this->successCode, '返回成功', $res ?: '');
    }

    //根据手机号码搜索佳人
    function get_by_phone(){
        $contact     = $this->request->get('contact');
        $wxapp_id    = $this->request->get('wxapp_id');
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');
        $where   = [];
        $where["wxapp_id"]=$wxapp_id;
        $res = ZhAuthenticationModel::where($where);
        if($contact){
            $res=$res->whereLike("contact","%".$contact."%");
        }
        $res=$res ->field("authentication_id,real_name,contact")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        return $this->ajaxReturn($this->successCode, '返回成功', $res );
    }

    function test(){
        $test="0";
        print_R(explode(",",$test));
    }

}

